﻿using System;
using System.IO;
using System.Reflection;
using System.Windows;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis;
using ICSharpCode.AvalonEdit;
using ICSharpCode.AvalonEdit.Highlighting;
using ICSharpCode.AvalonEdit.Highlighting.Xshd;
using ICSharpCode.AvalonEdit.CodeCompletion;
using ICSharpCode.AvalonEdit.Document;
using ICSharpCode.AvalonEdit.Rendering;
using System.Xml;
using Microsoft.Win32;
using System.Windows.Media;
using System.Windows.Input;
using System.Windows.Controls;
using ICSharpCode.AvalonEdit.Editing;
using System.Reflection.Metadata;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Scripting;
using System.Windows.Threading;
using Microsoft.CodeAnalysis.FindSymbols;
using System.Threading;
using HandyControl.Tools.Extension;
using System.Windows.Controls.Primitives;
using System.Xml.Linq;
using static SimpleCSharpInterpreter.App.ViewModel.MainViewModel;
using System.Collections.ObjectModel;
using HandyControl.Controls;
using System.Windows.Forms;
using System.Resources;

namespace SimpleCSharpInterpreter.App.Windows
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : System.Windows.Window
    {
        private Debugger _debugger;
        private bool _isDebugging = false;
        private int _currentLine = -1;
        private CompletionWindow _completionWindow;
        private static DocumentId _documentId;
        private AdhocWorkspace _workspace;
        private Project _project;
        private ContextualHintService _contextualHintService;
        public List<ErrorInfo> Errors { get; set; } = new List<ErrorInfo>();









        private ObservableCollection<ViewModel.MainViewModel.PropertyItem> _properties = new ObservableCollection<ViewModel.MainViewModel.PropertyItem>();
        private ObservableCollection<ResourceItem> _resources = new ObservableCollection<ResourceItem>();

        public MainWindow()
        {
            InitializeComponent();
            DataContext = this;

            LoadCustomHighlighting();
            InitializeRoslynWorkspace();
            SetupCompletion();


            //DataContext = this;

            // 初始化属性网格
            PropertyGrid2.ItemsSource = _properties;

            // 初始化资源管理器
            InitializeResourceExplorer();
            //resourceTxt.Foreground = new SolidColorBrush(Color.FromRgb(241, 241, 241)); // 深灰色
            // 初始化示例代码
            CodeEditor.Text = @"//using System;

/*
 * 这是一个C#控制台应用程序示例
 * 包含基础语法和常用功能演示
 */

// 1. 基本输入输出
Console.WriteLine(""欢迎来到C#控制台应用程序！"");
Console.Write(""请输入您的名字："");
string userName = Console.ReadLine();

// 2. 变量与常量
int a = 10;
const int b = 20;  // 常量
double pi = 3.14159;
bool isActive = true;
char initial = 'A';

// 3. 字符串插值
Console.WriteLine($""\n你好, {userName}！今天是 {DateTime.Now:yyyy-MM-dd}"");
Console.WriteLine($""圆周率约等于: {pi:F2}"");  // 保留两位小数

// 4. 数组和集合
int[] numbers = { 1, 2, 3, 4, 5 };
List<string> fruits = new() { ""苹果"", ""香蕉"", ""橙子"" };

// 5. 条件语句
Console.Write(""\n请输入一个数字："");
if(int.TryParse(Console.ReadLine(), out int number))
{
    if(number > 100)
        Console.WriteLine(""这个数字大于100"");
    else if(number > 0)
        Console.WriteLine(""这是一个正数"");
    else
        Console.WriteLine(""这是零或负数"");
}
else
{
    Console.WriteLine(""输入的不是有效数字！"");
}

// 6. 循环结构
Console.WriteLine(""\n数字1-5的平方："");
for(int i = 1; i <= 5; i++)
{
    Console.WriteLine($""{i} 的平方是 {i * i}"");
}

Console.WriteLine(""\n水果列表："");
foreach(var fruit in fruits)
{
    Console.WriteLine(fruit);
}

// 7. 方法调用
int sum = AddNumbers(a, b);
Console.WriteLine($""\n{a} + {b} = {sum}"");

PrintMessage(""这是一个方法调用的示例"");


// 9. 异常处理
try
{
    Console.Write(""\n请输入被除数："");
    int dividend = int.Parse(Console.ReadLine());
    Console.Write(""请输入除数："");
    int divisor = int.Parse(Console.ReadLine());
    
    Console.WriteLine($""结果是: {DivideNumbers(dividend, divisor)}"");
}
catch(DivideByZeroException)
{
    Console.WriteLine(""错误：除数不能为零！"");
}
catch(Exception ex)
{
    Console.WriteLine($""发生错误: {ex.Message}"");
}

// 10. 保持控制台打开
Console.WriteLine(""\n按任意键退出..."");
Console.Read();

// 方法定义
int AddNumbers(int x, int y) => x + y;

void PrintMessage(string msg)
{
    Console.WriteLine($""消息内容：{msg}"");
}

double DivideNumbers(int a, int b) => a / (double)b;


";
            SetupEnhancedCompletion();
            SetupParameterHinting();
            SetupQuickInfo();

            // 启用实时错误检查
            var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };
            timer.Tick += async (s, e) => await CheckForErrorsAsync();
            timer.Start();


            _contextualHintService = new ContextualHintService(CodeEditor, _workspace);

            // 添加键盘快捷键
            CodeEditor.TextArea.KeyDown += OnEditorKeyDown;
            CodeEditor.TextArea.TextEntered += OnTextEntered;
        }


        #region 新增 1.0.1

        private void InitializeResourceExplorer()
        {
            // 添加示例资源
            var solutionItem = new ResourceItem
            {
                Name = "解决方案",
                IsDirectory = true,
                Icon = GetFolderIcon()
            };

            var projectItem = new ResourceItem
            {
                Name = "ScriptProject",
                IsDirectory = true,
                Icon = GetFolderIcon()
            };

            var scriptItem = new ResourceItem
            {
                Name = "Script.cs",
                IsDirectory = false,
                Icon = GetFileIcon()
            };

            projectItem.Children.Add(scriptItem);
            solutionItem.Children.Add(projectItem);
            _resources.Add(solutionItem);

            ResourceExplorerTree.ItemsSource = _resources;
        }

        private ImageSource GetFolderIcon()
        {
            var geometry = Geometry.Parse("M12,20 L3,20 L3,4 L21,4 L21,15 L12,15 M7,12 L7,11 L17,11 L17,12 L7,12 M7,8 L7,7 L17,7 L17,8 L7,8 Z");
            return new DrawingImage(new GeometryDrawing(Brushes.Yellow, null, geometry));
        }

        private ImageSource GetFileIcon()
        {
            var geometry = Geometry.Parse("M14,2 L6,2 C4.9,2 4,2.9 4,4 L4,20 C4,21.1 4.9,22 6,22 L18,22 C19.1,22 20,21.1 20,20 L20,8 L14,2 M14,9 L14,3.5 L19.5,9 L14,9 Z");
            return new DrawingImage(new GeometryDrawing(Brushes.LightBlue, null, geometry));
        }

        private void RefreshProperties(string filter = "")
        {
            _properties.Clear();

            // 添加示例属性
            _properties.Add(new ViewModel.MainViewModel.PropertyItem
            {
                Name = "FileName",
                Value = "Script.cs",
                Type = "string"
            });

            _properties.Add(new ViewModel.MainViewModel.PropertyItem
            {
                Name = "IsModified",
                Value = "False",
                Type = "bool"
            });

            _properties.Add(new ViewModel.MainViewModel.PropertyItem
            {
                Name = "LineCount",
                Value = CodeEditor.LineCount.ToString(),
                Type = "int"
            });

            _properties.Add(new ViewModel.MainViewModel.PropertyItem
            {
                Name = "Encoding",
                Value = "UTF-8",
                Type = "string"
            });

            // 应用过滤
            if (!string.IsNullOrEmpty(filter))
            {
                foreach (var item in _properties.Where(p =>
                    !p.Name.Contains(filter)).ToList())
                {
                    _properties.Remove(item);
                }
            }
        }

        private void PropertySearchBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            RefreshProperties(PropertySearchBox.Text);
        }

        private void RefreshResourcesButton_Click(object sender, RoutedEventArgs e)
        {
            InitializeResourceExplorer();
        }

        private void AddResourceButton_Click(object sender, RoutedEventArgs e)
        {
            var dialog = new Microsoft.Win32.OpenFileDialog
            {
                Multiselect = true,
                Filter = "所有文件 (*.*)|*.*"
            };

            if (dialog.ShowDialog() == true)
            {
                foreach (var file in dialog.FileNames)
                {
                    var fileName = Path.GetFileName(file);
                    if (!_resources[0].Children[0].Children.Any(r => r.Name == fileName))
                    {
                        _resources[0].Children[0].Children.Add(new ResourceItem
                        {
                            Name = fileName,
                            FullPath = file,
                            IsDirectory = false,
                            Icon = GetFileIcon()
                        });
                    }
                }
            }
        }

        private void ResourceExplorerTree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (e.NewValue is ResourceItem item && !item.IsDirectory)
            {
                try
                {
                    var content = File.ReadAllText(item.FullPath);
                    CodeEditor.Text = content;
                    //更新标题
                    var fileName = Path.GetFileName(item.FullPath);
                    filename.Text = fileName;

                    // 更新属性
                    RefreshProperties();
                    _properties.Add(new ViewModel.MainViewModel.PropertyItem
                    {
                        Name = "LoadedFile",
                        Value = item.Name,
                        Type = "string"
                    });
                }
                catch (Exception ex)
                {
                    Growl.Error($"无法加载文件: {ex.Message}");
                }
            }
        }

        #endregion

        private async void OnTextEntered(object sender, TextCompositionEventArgs e)
        {
            // 当输入特定字符时触发提示
            if (e.Text == "." || e.Text == "(" || e.Text == ",")
            {
                await _contextualHintService.ShowContextualHintAsync();
            }
        }

        private async void OnEditorKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            // Ctrl+Space快捷键触发提示
            if (e.Key == Key.Space && Keyboard.Modifiers == ModifierKeys.Control)
            {
                e.Handled = true;
                await _contextualHintService.ShowContextualHintAsync();
            }
        }

        private void SetupEnhancedCompletion()
        {
            CodeEditor.TextArea.TextEntering += (sender, e) => {
                if (e.Text.Length > 0 && _completionWindow != null)
                {
                    if (!char.IsLetterOrDigit(e.Text[0]))
                    {
                        _completionWindow.CompletionList.RequestInsertion(e);
                    }
                }
            };

            CodeEditor.TextArea.TextEntered += async (sender, e) => {
                // 触发代码提示的字符（扩展更多触发点）
                var triggers = new[] { ".", " ", "(", ",", "=", ":" };
                if (triggers.Contains(e.Text))
                {
                    var document = UpdateDocument();
                    var service = CompletionService.GetService(document);
                    var position = CodeEditor.CaretOffset;

                    // 更智能的触发逻辑
                    var trigger = e.Text == "." ?
                        CompletionTrigger.CreateInsertionTrigger('.') :
                        CompletionTrigger.CreateInsertionTrigger(';');
                    CompletionTrigger.CreateInsertionTrigger(' ');


                    var completions = await service.GetCompletionsAsync(document, position, trigger);
                    if (!completions.Items.Any())
                    {
                        foreach (var item in triggers)
                        {
                            trigger = CompletionTrigger.CreateInsertionTrigger(item.ToCharArray()[0]);
                            if (completions.Items.Any())
                                break;
                        }
                    }
                    if (completions != null && completions.Items.Any())
                    {
                        _completionWindow = new CompletionWindow(CodeEditor.TextArea);
                        var data = _completionWindow.CompletionList.CompletionData;

                        // 增强的提示数据展示
                        foreach (var item in completions.Items.OrderBy(i => i.SortText))
                        {
                            data.Add(new EnhancedCompletionData(
                                item.DisplayText,
                                item.DisplayTextPrefix,
                                item.InlineDescription,
                                GetGlyph(item.Tags)
                            ));
                        }

                        // 智能过滤
                        _completionWindow.CompletionList.ListBox.SelectionChanged += (s, args) => {
                            if (_completionWindow.CompletionList.SelectedItem != null)
                            {
                                var selected = _completionWindow.CompletionList.SelectedItem;
                                _completionWindow.CompletionList.DataContext = selected.Description;
                            }
                        };

                        _completionWindow.Show();
                        _completionWindow.Closed += (o, args) => _completionWindow = null;
                    }
                }
            };
        }
        private void Thumb_DragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e)
        {
            // 获取当前行定义
            var rowDefinition = gridmsg.RowDefinitions[2];
            double newHeight = rowDefinition.ActualHeight - e.VerticalChange;

            // 限制最小和最大高度
            if (newHeight < 50) newHeight = 50;
            if (newHeight > 300) newHeight = 300;

            rowDefinition.Height = new GridLength(newHeight);
        }
        private bool isDarkTheme = true;

        private void ThemeToggleButton_Click(object sender, RoutedEventArgs e)
        {
            isDarkTheme = !isDarkTheme;

            if (isDarkTheme)
            {
                // 切换到暗色主题
                Resources["BackgroundColorCustom"] = Resources["DarkBackgroundColor"];
                Resources["TextColorCustom"] = Resources["DarkTextColor"];
                Resources["ControlBackgroundCustom"] = Resources["DarkControlBackground"];
                CodeEditor.Background = new SolidColorBrush(Color.FromRgb(0, 25, 75)); // 深灰色
                OutputBox.Background = new SolidColorBrush(Color.FromRgb(30, 30, 30)); // 深灰色
                OutputBox.Foreground = new SolidColorBrush(Color.FromRgb(241, 241, 241)); // 深灰色
                //resourceTxt.Foreground = new SolidColorBrush(Color.FromRgb(241, 241, 241)); // 深灰色
                ThemeToggleButton.Content = "亮色主题";
                Growl.Info("切换为暗色主题");
            }
            else
            {
                // 切换到亮色主题
                Resources["BackgroundColor"] = Resources["LightBackgroundColor"];
                Resources["TextColor"] = Resources["LightTextColor"];
                Resources["ControlBackground"] = Resources["LightControlBackground"];
                CodeEditor.Background = new SolidColorBrush(Color.FromRgb(241, 241, 241)); // 
                OutputBox.Background = new SolidColorBrush(Color.FromRgb(241, 241, 241)); // 
                OutputBox.Foreground = new SolidColorBrush(Color.FromRgb(30, 30, 30)); // 深灰色
                //resourceTxt.Foreground = new SolidColorBrush(Color.FromRgb(30, 30, 30)); // 深灰色
                ThemeToggleButton.Content = "暗色主题";
                Growl.Info("切换为亮色主题");

            }

            // 强制刷新所有动态资源
            this.UpdateLayout();
        }
        private static ImageSource GetGlyph(IEnumerable<string> tags)
        {
            var image = new DrawingImage();
            var drawingGroup = new DrawingGroup();

            if (tags.Contains("Field"))
                drawingGroup.Children.Add(new GeometryDrawing(Brushes.LightBlue, null, Geometry.Parse("M0,0 L8,0 L8,8 L0,8 Z")));
            else if (tags.Contains("Method"))
                drawingGroup.Children.Add(new GeometryDrawing(Brushes.Yellow, null, Geometry.Parse("M0,0 L8,4 L0,8 Z")));

            image.Drawing = drawingGroup;
            return image;
        }



        //protected override void OnKeyDown(KeyEventArgs e)
        //{

        //    // 其他按键处理...
        //}

        private async void TriggerCompletion()
        {
            var document = UpdateDocument();
            var service = CompletionService.GetService(document);
            var position = CodeEditor.CaretOffset;

            var completions = await service.GetCompletionsAsync(
                document,
                position,
                CompletionTrigger.CreateInsertionTrigger(';')
            );

            // 显示提示窗口...
        }




        protected override void OnKeyDown(System.Windows.Input.KeyEventArgs e)
        {
            base.OnKeyDown(e);

            if (e.Key == Key.Space && Keyboard.Modifiers == ModifierKeys.Control)
            {
                e.Handled = true;
                TriggerCompletion();
            }

            if (e.Key == Key.Space && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
            {
                e.Handled = true;
                //ShowCompletion();
            }
            else if (e.Key == Key.F5)
            {
                ExecuteCode();
                e.Handled = true;
            }
            else if (e.Key == Key.F6)
            {
                if (_isDebugging)
                    StopDebugging();
                else
                    StartDebugging();
                e.Handled = true;
            }
            else if (e.Key == Key.F7 && _isDebugging)
            {
                StepButton_Click(null, null);
                e.Handled = true;
            }
        }


















        private void SetupParameterHinting()
        {
            CodeEditor.TextArea.TextEntered += async (sender, e) =>
            {
                if (e.Text == "(") // 方法调用时触发
                {
                    var document = UpdateDocument();
                    var syntaxTree = await document.GetSyntaxTreeAsync();
                    var semanticModel = await document.GetSemanticModelAsync();
                    var position = CodeEditor.CaretOffset;

                    var symbol = SymbolFinder.FindSymbolAtPosition(semanticModel, position, _workspace);
                    if (symbol is IMethodSymbol method)
                    {
                        // 方案3：如果类支持初始化后配置
                        var hint = new OverloadViewer
                        {
                            Text = CodeEditor.Text // 假设有可写属性
                        };
                        // 方案1：使用正确的API调用方式（假设类有不同签名的方法）
                        //var hint = new OverloadViewer(CodeEditor.TextArea); // 需要传入TextArea参数



                        // 方案2：调用显示方法
                        hint.Show();

                        // 方案3：通过数据绑定
                        hint.DataContext = method;


                        hint.Visibility = Visibility.Visible; // 使用属性控制显示
                    }
                }
            };
        }
        private void SetupQuickInfo()
        {
            CodeEditor.TextArea.TextView.MouseHover += async (sender, e) =>
            {
                var position = CodeEditor.TextArea.TextView.GetPositionFloor(e.GetPosition(CodeEditor.TextArea.TextView));
                var document = UpdateDocument();
                var semanticModel = await document.GetSemanticModelAsync();

                //var symbol = Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindSymbolAtPosition(semanticModel, position.Value, _workspace);
                // 更安全的调用方式（带null检查）
                if (position.HasValue)
                {
                    // 使用异步版本（推荐）
                    // 获取文档中的字符偏移量
                    int offset = CodeEditor.Document.GetOffset(position.Value.Location);
                    var symbol = await SymbolFinder.FindSymbolAtPositionAsync(
                        semanticModel,
                        offset,  // 使用转换后的int值
                        _workspace
                    );

                    // 或者保持同步调用（不推荐）
                    // var symbol = SymbolFinder.FindSymbolAtPosition(
                    //     semanticModel,
                    //     position.Value,
                    //     _workspace,
                    //     cancellationToken);
                    if (symbol != null)
                    {
                        var toolTip = new System.Windows.Controls.ToolTip { Content = symbol.ToDisplayString() };
                        ToolTipService.SetToolTip(CodeEditor, toolTip);
                    }
                }

            };
        }

        private void LoadCustomHighlighting()
        {
            try
            {
                using (var stream = typeof(MainWindow).Assembly.GetManifestResourceStream("EnhancedCSharpInterpreter.Resources.CSharp.xshd"))
                {
                    if (stream != null)
                    {
                        using (var reader = new XmlTextReader(stream))
                        {
                            CodeEditor.SyntaxHighlighting = HighlightingLoader.Load(reader, HighlightingManager.Instance);
                        }
                    }
                    else
                    {
                        CodeEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
                    }
                }
            }
            catch
            {
                CodeEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
            }
        }

        private void InitializeRoslynWorkspace()
        {
            _workspace = new AdhocWorkspace();
            var projectInfo = ProjectInfo.Create(
                ProjectId.CreateNewId(),
                VersionStamp.Create(),
                "ScriptProject",
                "ScriptProject",
                LanguageNames.CSharp,
                metadataReferences: GetReferences());

            _project = _workspace.AddProject(projectInfo);
            UpdateDocument();
        }

        private Microsoft.CodeAnalysis.Document UpdateDocument()
        {
            var sourceText = SourceText.From(CodeEditor.Text);
            var document = _project.AddDocument("Script.cs", sourceText);
            _documentId = document.Id;
            _project = document.Project;
            _workspace.TryApplyChanges(_project.Solution);

            return document;
        }

        private void SetupCompletion()
        {
            CodeEditor.TextArea.TextEntering += (sender, e) =>
            {
                if (e.Text.Length > 0 && _completionWindow != null)
                {
                    if (!char.IsLetterOrDigit(e.Text[0]))
                    {
                        _completionWindow.CompletionList.RequestInsertion(e);
                    }
                }
            };

            CodeEditor.TextArea.TextEntered += async (sender, e) =>
            {
                if (e.Text == "." || e.Text == " " || e.Text == "(")
                {
                    var document = UpdateDocument();
                    //var document = _workspace.GetDocument(_documentId);
                    var service = CompletionService.GetService(document);
                    var position = CodeEditor.CaretOffset;
                    //var trigger = new CompletionTrigger(CompletionTriggerKind.Insertion, e.Text[0]);
                    var trigger = new CompletionTrigger();
                    if (service is null)
                        return;
                    var completions = await service.GetCompletionsAsync(document, position, trigger);

                    if (completions != null && completions.Items.Any())
                    {
                        _completionWindow = new CompletionWindow(CodeEditor.TextArea);
                        var data = _completionWindow.CompletionList.CompletionData;

                        foreach (var item in completions.Items)
                        {
                            data.Add(new MyCompletionData(item.DisplayText, item.DisplayText));
                        }

                        _completionWindow.Show();
                        _completionWindow.Closed += (o, args) => _completionWindow = null;
                    }
                }
            };
        }

        private IEnumerable<MetadataReference> GetReferences()
        {
            var references = new List<MetadataReference>();

            // 添加核心程序集
            references.Add(MetadataReference.CreateFromFile(typeof(object).Assembly.Location));
            references.Add(MetadataReference.CreateFromFile(typeof(Console).Assembly.Location));
            references.Add(MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location));
            references.Add(MetadataReference.CreateFromFile(typeof(System.Runtime.AssemblyTargetedPatchBandAttribute).Assembly.Location));

            // 添加当前程序集可能需要的引用
            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                if (!assembly.IsDynamic && !string.IsNullOrEmpty(assembly.Location))
                {
                    references.Add(MetadataReference.CreateFromFile(assembly.Location));
                }
            }

            return references;
        }

        private void RunButton_Click(object sender, RoutedEventArgs e)
        {
            ExecuteCode();
        }




        private void Close_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }



        private void ExecuteCode()
        {
            try
            {
                string code = CodeEditor.Text;
                string script = WrapCodeInClass(code);

                var compilation = CSharpCompilation.Create("DynamicScript")
                    .WithOptions(new CSharpCompilationOptions(OutputKind.ConsoleApplication))
                    .AddReferences(GetReferences())
                    .AddSyntaxTrees(CSharpSyntaxTree.ParseText(script));

                using (var ms = new MemoryStream())
                {
                    EmitResult result = compilation.Emit(ms);

                    if (!result.Success)
                    {
                        Errors.Clear();

                        foreach (var diagnostic in result.Diagnostics)
                        {
                            if (diagnostic.Severity == DiagnosticSeverity.Error)
                            {
                                var lineSpan = diagnostic.Location.GetLineSpan();
                                Errors.Add(new ErrorInfo
                                {
                                    Line = lineSpan.StartLinePosition.Line + 1,
                                    Column = lineSpan.StartLinePosition.Character + 1,
                                    Message = diagnostic.GetMessage()
                                });
                                Growl.Error($"报错：{diagnostic.GetMessage()}");
                            }
                        }

                        ErrorGrid.Items.Refresh();
                        //TabControl.SelectedIndex = 1;
                    }
                    else
                    {
                        ms.Seek(0, SeekOrigin.Begin);

                        var originalConsoleOut = Console.Out;
                        var consoleOutput = new StringWriter();
                        Console.SetOut(consoleOutput);

                        try
                        {
                            var assembly = Assembly.Load(ms.ToArray());
                            var entryPoint = assembly.EntryPoint;
                            entryPoint.Invoke(null, new object[] { new string[0] });

                            OutputBox.Text = consoleOutput.ToString();
                            Errors.Clear();
                            ErrorGrid.Items.Refresh();
                            //TabControl.SelectedIndex = 0;
                        }
                        catch (Exception ex)
                        {
                            OutputBox.Text = $"执行错误: {GetFriendlyErrorMessage(ex)}";
                        }
                        finally
                        {
                            Console.SetOut(originalConsoleOut);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                OutputBox.Text = $"错误: {GetFriendlyErrorMessage(ex)}";
            }
            finally
            {
                Growl.Success("执行完成");
            }
        }

        private string GetFriendlyErrorMessage(Exception ex)
        {
            if (ex is TargetInvocationException tie && tie.InnerException != null)
            {
                ex = tie.InnerException;
            }

            switch (ex)
            {
                case NullReferenceException nre:
                    return "空引用异常: " + nre.Message;
                case ArgumentException ae:
                    return "参数错误: " + ae.Message;
                case InvalidOperationException ioe:
                    return "无效操作: " + ioe.Message;
                default:
                    return ex.Message;
            }
        }

        private string WrapCodeInClass(string code)
        {
            return $@"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class ScriptRunner
{{
    public static void Main(string[] args)
    {{
        {code}
    }}
}}";
        }





        private void DebugButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_isDebugging)
                {
                    StopDebugging();
                }
                else
                {
                    StartDebugging();
                }
            }
            catch (Exception ex)
            {

                Growl.Error(ex.Message);
            }
            finally
            {
                Growl.Success("调试完成");
            }
        }

        private void StartDebugging()
        {
            try
            {
                string code = CodeEditor.Text;
                string script = WrapCodeInClass(code);

                _debugger = new Debugger(script, GetReferences());
                _debugger.BreakpointHit += Debugger_BreakpointHit;
                _debugger.ExecutionComplete += Debugger_ExecutionComplete;

                _isDebugging = true;
                DebugButton.Content = "停止调试";
                StepButton.IsEnabled = true;

                _debugger.Start();
            }
            catch (Exception ex)
            {
                OutputBox.Text = $"调试启动失败: {ex.Message}";
            }
        }

        private void StopDebugging()
        {
            _isDebugging = false;
            DebugButton.Content = "调试(F6)";
            StepButton.IsEnabled = false;
            _debugger?.Stop();
            ClearCurrentLineHighlight();
        }

        private void StepButton_Click(object sender, RoutedEventArgs e)
        {
            _debugger?.Step();
        }

        private void Debugger_BreakpointHit(object sender, BreakpointEventArgs e)
        {
            Dispatcher.Invoke(() =>
            {
                _currentLine = e.LineNumber;
                HighlightCurrentLine();
                OutputBox.Text += $"在行 {e.LineNumber} 暂停\n";
            });
        }

        private void Debugger_ExecutionComplete(object sender, EventArgs e)
        {
            Dispatcher.Invoke(() =>
            {
                _isDebugging = false;
                DebugButton.Content = "调试(F6)";
                StepButton.IsEnabled = false;
                ClearCurrentLineHighlight();
                OutputBox.Text += "调试完成\n";
            });
        }

        private void HighlightCurrentLine()
        {
            if (_currentLine >= 0)
            {
                var line = CodeEditor.Document.GetLineByNumber(_currentLine);
                CodeEditor.TextArea.TextView.BackgroundRenderers.Add(
                    new CurrentLineBackgroundRenderer(line, Colors.Yellow));
                CodeEditor.TextArea.TextView.InvalidateLayer(KnownLayer.Background);
            }
        }

        private void ClearCurrentLineHighlight()
        {
            CodeEditor.TextArea.TextView.BackgroundRenderers.Clear();
            CodeEditor.TextArea.TextView.InvalidateLayer(KnownLayer.Background);
            _currentLine = -1;
        }
        private void TitleBar_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                this.DragMove();
            }
        }

        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            Growl.Info("请选择保存路径...");
            var saveDialog = new Microsoft.Win32.SaveFileDialog()
            {
                Filter = "C# 文件 (*.cs)|*.cs|所有文件 (*.*)|*.*",
                DefaultExt = ".cs",
                Title = "保存代码"
            };

            if (saveDialog.ShowDialog() == true)
            {
                try
                {
                    File.WriteAllText(saveDialog.FileName, CodeEditor.Text);
                    //MessageBox.Show("保存成功!", "信息", MessageBoxButton.OK, MessageBoxImage.Information);
                    Growl.Error("保存成功!");
                }
                catch (Exception ex)
                {
                    //MessageBox.Show($"保存失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    Growl.Error($"保存失败: {ex.Message}");
                }
            }
        }

        private void LoadButton_Click(object sender, RoutedEventArgs e)
        {
            Growl.Info("加载中...");
            var openDialog = new Microsoft.Win32.OpenFileDialog()
            {
                Filter = "C# 文件 (*.cs)|*.cs|所有文件 (*.*)|*.*",
                DefaultExt = ".cs",
                Title = "加载代码"
            };

            if (openDialog.ShowDialog() == true)
            {
                try
                {
                    CodeEditor.Text = File.ReadAllText(openDialog.FileName);
                }
                catch (Exception ex)
                {
                    //MessageBox.Show($"加载失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    Growl.Error($"加载失败: {ex.Message}");
                }
            }
        }

        private void ClearButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                OutputBox.Text = string.Empty;
                Errors.Clear();
                ErrorGrid.Items.Refresh();
            }
            catch (Exception ex)
            {

                throw;
            }
            finally
            {
                Growl.Info("已清空");
            }
        }

        private void ErrorGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (ErrorGrid.SelectedItem is ErrorInfo error)
            {
                CodeEditor.ScrollTo(error.Line, error.Column);
                CodeEditor.Focus();
            }
        }
        private async Task CheckForErrorsAsync()
        {
            var document = UpdateDocument();
            var diagnostics = document.GetSemanticModelAsync().Result.GetDiagnostics(null, default);

            var textView = CodeEditor.TextArea.TextView;
            //textView.LineTransformers.RemoveAll(t => t is ErrorLineTransformer);

            var errorTransformer = new ErrorLineTransformer(diagnostics);
            textView.LineTransformers.Add(errorTransformer);
        }
        private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.F5)
            {
                ExecuteCode();
                e.Handled = true;
            }
            else if (e.Key == Key.F6)
            {
                if (_isDebugging)
                    StopDebugging();
                else
                    StartDebugging();
                e.Handled = true;
            }
            else if (e.Key == Key.F7 && _isDebugging)
            {
                StepButton_Click(null, null);
                e.Handled = true;
            }
        }




        private class ContextualHintService
        {
            private readonly TextEditor _editor;
            private readonly AdhocWorkspace _workspace;
            private Popup _hintPopup;
            private TextBlock _hintContent;

            public ContextualHintService(TextEditor editor, AdhocWorkspace workspace)
            {
                _editor = editor;
                _workspace = workspace;
                InitializePopup();
            }

            private void InitializePopup()
            {
                _hintPopup = new Popup
                {
                    Placement = PlacementMode.Relative,
                    PlacementTarget = _editor,
                    StaysOpen = false,
                    AllowsTransparency = true
                };

                _hintContent = new TextBlock
                {
                    Background = Brushes.DarkSlateGray,
                    Foreground = Brushes.White,
                    Padding = new Thickness(5),
                    MaxWidth = 300,
                    TextWrapping = TextWrapping.Wrap
                };

                _hintPopup.Child = _hintContent;
            }

            public async Task ShowContextualHintAsync()
            {
                var document = GetCurrentDocument();
                var position = _editor.CaretOffset;
                var semanticModel = await document.GetSemanticModelAsync();

                // 获取当前符号
                var symbol = await SymbolFinder.FindSymbolAtPositionAsync(semanticModel, position, _workspace);
                if (symbol == null) return;

                // 获取符号的XML文档注释
                var documentation = symbol.GetDocumentationCommentXml();
                if (string.IsNullOrEmpty(documentation)) return;

                // 解析XML文档注释
                var doc = XDocument.Parse($"<root>{documentation}</root>");
                var summary = doc.Descendants("summary").FirstOrDefault()?.Value.Trim();

                if (!string.IsNullOrEmpty(summary))
                {
                    _hintContent.Text = $"{symbol.ToDisplayString()}\n\n{summary}";

                    // 计算弹出位置
                    var caret = _editor.TextArea.Caret;
                    var positionInEditor = caret.Position;
                    var textView = _editor.TextArea.TextView;
                    var visualPosition = textView.GetVisualPosition(positionInEditor, VisualYPosition.LineBottom);

                    _hintPopup.PlacementRectangle = new Rect(
                        visualPosition.X,
                        visualPosition.Y,
                        0, 0);

                    _hintPopup.IsOpen = true;
                }
            }

            private Microsoft.CodeAnalysis.Document GetCurrentDocument()
            {
                var sourceText = SourceText.From(_editor.Text);
                return _workspace.CurrentSolution.GetDocument(_documentId) ??
                       _workspace.AddDocument(_documentId.ProjectId, "Script.cs", sourceText);
            }
        }



        class EnhancedCompletionData : ICompletionData
        {
            public EnhancedCompletionData(string text, string displayText, string description, ImageSource image)
            {
                Text = text;
                Content = displayText;
                Description = description;
                Image = image;
            }

            public ImageSource Image { get; }
            public string Text { get; }
            public object Content { get; }
            public object Description { get; }
            public double Priority => 0;

            public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs)
            {
                textArea.Document.Replace(completionSegment, Text);
            }
        }




        class ErrorLineTransformer : DocumentColorizingTransformer
        {
            private readonly Diagnostic[] _diagnostics;

            public ErrorLineTransformer(IEnumerable<Diagnostic> diagnostics)
            {
                _diagnostics = diagnostics.ToArray();
            }

            protected override void ColorizeLine(DocumentLine line)
            {
                foreach (var diagnostic in _diagnostics.Where(d =>
                    d.Location.GetLineSpan().StartLinePosition.Line == line.LineNumber - 1))
                {
                    ChangeLinePart(
                        line.Offset,
                        line.EndOffset,
                        visualLine => visualLine.TextRunProperties.SetBackgroundBrush(Brushes.DarkRed)
                    );
                }
            }
        }
        class MyCompletionData : ICompletionData
        {
            public MyCompletionData(string text, string description)
            {
                Text = text;
                Description = description;
            }

            public System.Windows.Media.ImageSource Image => null;
            public string Text { get; }
            public object Content => Text;
            public object Description { get; }
            public double Priority => 0;

            public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs)
            {
                textArea.Document.Replace(completionSegment, Text);
            }
        }

    }
    class CurrentLineBackgroundRenderer : IBackgroundRenderer
    {
        private readonly DocumentLine _line;
        private readonly Color _color;

        public CurrentLineBackgroundRenderer(DocumentLine line, Color color)
        {
            _line = line;
            _color = color;
        }

        public KnownLayer Layer => KnownLayer.Background;

        public void Draw(TextView textView, DrawingContext drawingContext)
        {
            if (_line.IsDeleted) return;

            var segment = new ICSharpCode.AvalonEdit.Document.TextSegment()
            {
                StartOffset = _line.Offset,
                Length = _line.Length
            };

            foreach (var rect in BackgroundGeometryBuilder.GetRectsForSegment(textView, segment))
            {
                drawingContext.DrawRectangle(
                    new SolidColorBrush(_color),
                    null,
                    new Rect(rect.Location, new Size(textView.ActualWidth, rect.Height)));
            }
        }
    }









    // 简单的调试器类
    class Debugger
    {
        public event EventHandler<BreakpointEventArgs> BreakpointHit;
        public event EventHandler ExecutionComplete;

        private readonly string _script;
        private readonly IEnumerable<MetadataReference> _references;
        private ScriptState _state;
        private bool _isRunning;

        public Debugger(string script, IEnumerable<MetadataReference> references)
        {
            _script = script;
            _references = references;
        }

        public void Start()
        {
            _isRunning = true;
            Task.Run(() => ExecuteScript());
        }

        public void Stop()
        {
            _isRunning = false;
        }

        public void Step()
        {
            // 实现单步执行逻辑
        }

        private async Task ExecuteScript()
        {
            try
            {
                var compilation = CSharpCompilation.Create("DebugScript")
                    .WithOptions(new CSharpCompilationOptions(OutputKind.ConsoleApplication))
                    .AddReferences(_references)
                    .AddSyntaxTrees(CSharpSyntaxTree.ParseText(_script));

                using (var ms = new MemoryStream())
                {
                    var result = compilation.Emit(ms);

                    if (result.Success)
                    {
                        ms.Seek(0, SeekOrigin.Begin);
                        var assembly = Assembly.Load(ms.ToArray());
                        var entryPoint = assembly.EntryPoint;

                        // 这里需要更复杂的执行控制来实现调试
                        // 实际项目中应该使用 Roslyn Scripting API
                        var consoleOutput = new StringWriter();
                        var originalConsoleOut = Console.Out;
                        Console.SetOut(consoleOutput);

                        try
                        {
                            entryPoint.Invoke(null, new object[] { new string[0] });
                            ExecutionComplete?.Invoke(this, EventArgs.Empty);
                        }
                        finally
                        {
                            Console.SetOut(originalConsoleOut);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"调试错误: {ex}");
            }
        }
    }

    class BreakpointEventArgs : EventArgs
    {
        public int LineNumber { get; }

        public BreakpointEventArgs(int lineNumber)
        {
            LineNumber = lineNumber;
        }
    }







    public class ErrorInfo
    {
        public int Line { get; set; }
        public int Column { get; set; }
        public string Message { get; set; }
    }
}
